<template>
  <view class="login">
    <u-navbar title="登录" bgColor="#f56c6c" :placeholder="true">
      <template #left>
        <u-icon name="home-fill" size="19" @click="toHome"></u-icon>
      </template>
    </u-navbar>
    <button class="avatar" open-type="chooseAvatar" @chooseavatar="chooseAvatar">
      <image class="avatar" :src="photo"></image>
    </button>
    <view class="form">
      <view>
        <text>昵称</text>
        <input id="input" type="nickname" @blur="nicknameBlur" v-model="nickname" placeholder="请输入昵称"/>
      </view>
    </view>
    <view class="button">
      <u-button @tap="login" text="登录" type="primary" color="#f56c6c" :customStyle="{width: '150px'}"></u-button>
    </view>
    <u-toast ref="uToastRef"></u-toast>
  </view>
</template>

<script lang='ts' setup>
import {getCurrentInstance, ref} from "vue";

const { proxy }: any = getCurrentInstance()
const code = ref('')
const photo = ref('https://mmbiz.qpic.cn/mmbiz/icTdbqWNOwNRna42FI242Lcia07jQodd2FJGIYQfG0LAJGFxM4FbnQP6yfMxBgJ0F3YRqJCJ1aPAK2dQagdusBZg/0')
const nickname = ref('')
const uToastRef = ref()

const chooseAvatar = (e: any) => {
  const { avatarUrl } = e.detail;
  photo.value = avatarUrl;
}

const nicknameBlur = () => {
  uni.createSelectorQuery().in(proxy).select('#input').fields({
    properties: ['value']
  },()=>{}).exec((res)=>{
    nickname.value = res[0].value
  })
}

const login = () => {
  if(uni.$u.test.rangeLength(nickname.value, [2, 15])){
    console.log(photo.value)
    uni.login({
      success (res) {
        if (res.code) {
			code.value = res.code
			let data = {
				code: code.value,
				nickname: nickname.value,
				photo: photo.value
			}
          //提交Ajax请求，执行登陆或注册
          proxy.ajax(proxy.api.loginOrRegister, 'POST', data, function(resp: any) {
            let msg = resp.data.msg
            let userInfo = resp.data.userInfo
            uni.uploadFile({
				url: proxy.api.updatePhoto,
				filePath: photo.value,
				name: 'file',
				formData: {
					userId: userInfo.id
				},
				success: (res:any) => {
					let r = JSON.parse(res.data)
					uToastRef.value.show({
						message: msg,
						type: 'success',
						duration: 1200,
						complete: function() {
							let token = resp.data.token
							//把Token保存到Storage
							uni.setStorageSync('token', token)
							userInfo["photo"] = r.filename
							userInfo["nickname"] = nickname.value
							uni.setStorageSync('info',userInfo)
							uni.navigateTo({
								url: "/pages/mine/mine"
							})
						}
					})
				}
            })
          })
        }
      }
    })
  }
}

const toHome = () => {
  uni.navigateTo({
    url: "/pages/index/index"
  })
}
</script>

<style lang='scss' scoped>
@import "style.scss";
</style>